import Vue from 'vue'
import Vuex from 'vuex'
import { getUserInfoAPI, getUserProfile } from '@/api/userapi.js'

Vue.use(Vuex)

// 默认state是一个空的大对象
let initState = {
  tokenInfo: {},
  userInfo: {},
  userProfile: {}
}

// 取出本地中的state数据，赋值给state，如果不为空，JSON转换出来再次赋值
const satateStr = localStorage.getItem('state')
if (satateStr) {
  initState = JSON.parse(satateStr)
}

export default new Vuex.Store({
  state: initState,
  mutations: {
    updateTokenInfo (state, payload) {
      state.tokenInfo = payload
      // 调用存储的mutations方法，使用this.commit方法实现，，this.是指
      this.commit('saveStateToStorage')
    },
    // 将state中的数据存储到本地localstorage中
    saveStateToStorage (state) {
      localStorage.setItem('state', JSON.stringify(state))
    },
    updateUserInfo (state, payload) {
      state.userInfo = payload
      this.commit('saveStateToStorage')
    },
    // 详情页的数据转存
    updatUserProfile (state, payload) {
      state.userProfile = payload
      this.commit('saveStateToStorage')
    },
    clearState (state) {
      state.tokenInfo = {}
      state.userInfo = {}
      state.userProfile = {}
      this.commit('saveStateToStorage')
    }
  },
  actions: {
    // 请求数据
    async initUserinfo (ctx) {
      const { data: res } = await getUserInfoAPI()
      if (res.message === 'OK') {
        // TODO，转存到mutation
        ctx.commit('updateUserInfo', res.data)
      }
    },
    async initUserProfile (ctx) {
      const { data: res } = await getUserProfile()
      if (res.message === 'OK') {
        ctx.commit('updatUserProfile', res.data)
      }
    }
  },
  getters: {
    userAvatar (state) {
      let imgSrc = 'https://img.alicdn.com/imgextra/i2/O1CN018r2wCf1QVnfrS9fYW_!!6000000001982-2-tps-986-340.png_490x490q100.jpg_.webp'
      if (state.userInfo.photo) {
        imgSrc = state.userInfo.photo
      }
      return imgSrc
    }
  },
  modules: {

  }

})
